#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Annotated
from fastapi import APIRouter, Depends, Path, Query, Request

from app.schema import (
    CreateConservationParam,
    UpdateConservationParam,
    GetConservationList,
    GetConservationDetail, CreateKnowledgeBaseParam,
)
from app.service.conservation_service import conservation_service
from app.service.knowledge_base_service import knowledge_base_service
from common.pagination import DependsPagination, paging_data
from common.response.response_schema import ResponseModel, response_base
from common.security.jwt import DependsJwtAuth
from common.security.permission import RequestPermission
from database.db_mysql import CurrentSession
from utils.serializers import select_as_dict

router = APIRouter()


@router.post('', summary='创建会话', dependencies=[DependsJwtAuth])
async def create_conservation(request: Request, obj: CreateConservationParam) -> ResponseModel:
    conservation = await conservation_service.add(request=request, obj=obj)
    conservation_data = GetConservationList(**select_as_dict(conservation))
    return response_base.success(data=conservation_data)


@router.put('/{conservation_uuid}', summary='更新会话信息', dependencies=[DependsJwtAuth])
async def update_conservation(request: Request, conservation_uuid: Annotated[str, Path(...)],
                              obj: UpdateConservationParam) -> ResponseModel:
    count = await conservation_service.update(request=request, conservation_uuid=conservation_uuid, obj=obj)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.put('/{conservation_uuid}/status', summary='修改会话状态', dependencies=[DependsJwtAuth])
async def update_conservation_status(request: Request, conservation_uuid: Annotated[str, Path(...)],
                                     status: Annotated[bool, Query()]) -> ResponseModel:
    count = await conservation_service.update_status(request=request, conservation_uuid=conservation_uuid,
                                                     status=status)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.get('/all', summary='查看会话信息', dependencies=[DependsJwtAuth])
async def get_all_conservations(
    request: Request,
    agent_uuid: Annotated[str | None, Query()] = None,
    user_uuid: Annotated[str | None, Query()] = None,
    name: Annotated[str | None, Query()] = None,
) -> ResponseModel:
    # 获取所有会话
    conservations = await conservation_service.get_all(user_uuid=user_uuid, agent_uuid=agent_uuid, name=name)

    # 过滤出和当前用户相关的会话
    filtered_conservations = [
        conservation for conservation in conservations
        if conservation.user_uuid == request.user.uuid
    ]

    # 转换为响应所需的格式
    data = [GetConservationList(**select_as_dict(conservation)) for conservation in filtered_conservations]
    return response_base.success(data=data)


@router.get('/{conservation_uuid}', summary='查看会话信息', dependencies=[DependsJwtAuth])
async def get_conservation_info(request: Request, conservation_uuid: Annotated[str, Path(...)]) -> ResponseModel:
    current_conservation = await conservation_service.get_with_relation(request=request,
                                                                        conservation_uuid=conservation_uuid)
    data = GetConservationDetail(**select_as_dict(current_conservation))
    return response_base.success(data=data)


@router.get(
    '',
    summary='分页获取所有会话',
    dependencies=[
        DependsJwtAuth,
        DependsPagination,
    ],
)
async def get_pagination_conservations(
        request: Request,
        db: CurrentSession,
        name: Annotated[str | None, Query()] = None,
        status: Annotated[int | None, Query()] = None,
):
    conservation_select = await conservation_service.get_select(user_uuid=request.user.uuid, name=name, status=status)
    page_data = await paging_data(db, conservation_select, GetConservationList)
    return response_base.success(data=page_data)


@router.delete(
    path='/{conservation_uuid}',
    summary='删除会话',
    description='删除后会话将从数据库中删除',
    dependencies=[DependsJwtAuth, Depends(RequestPermission('sys:conservation:del'))],
)
async def delete_conservation(request: Request, conservation_uuid: Annotated[str, Path(...)]) -> ResponseModel:
    count = await conservation_service.delete(request=request, conservation_uuid=conservation_uuid)
    if count > 0:
        return response_base.success()
    return response_base.fail()
